package cn.xenosp.server.common.system.impl;

import cn.xenosp.server.common.tools.ServiceUtil;
import cn.xenosp.server.common.system.AbstractTargetOperatingSystem;
import cn.xenosp.server.module.third_server.entity.NginxEntity;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 项目名： nginx-web
 * 包路径： cn.xenosp.nginx.common.system.impl
 * 作者：   TongHui
 * 创建时间: 2024-07-25 16:34
 * 描述: TODO
 * 版本: 1.0
 */
@Slf4j
public class WindowsSystem extends AbstractTargetOperatingSystem {

    private static final String USER_HOME = System.getProperty("user.home") + File.separator + "nginx";
    private static final String START = "start.bat";
    private static final String STOP = "stop.bat";
    private static final String RESTART = "restart.bat";
//    private Logs logs = Logs.getInstance("WINDWOS 日志信息", WindowsSystem.class);

    @Override
    public void createScript(String serverName, String startPaht, String configPath) {
        int index = startPaht.lastIndexOf("\\");
        File nginx = new File(startPaht.substring(0, index) + File.separator + serverName);
        if (!nginx.exists()) {
            nginx.mkdirs();
        }

        createStartScript(serverName, startPaht, configPath);
        createStopScript(serverName, startPaht, configPath);
    }

    private void createStartScript(String serverName, String startPaht, String configPath) {
        String script = "@echo off\n" +
                "echo Starting Nginx...\n" +
                "start \"\" \"" + startPaht + "\"\n" +
                "echo Nginx has been started.\n" +
                "pause";
        int index = startPaht.lastIndexOf("\\");
        // 使用try-with-resources语句自动关闭资源
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(startPaht.substring(0, index) + File.separator + serverName + File.separator + serverName + "_" + START))) {
            // 写入脚本内容到文件
            writer.write(script);

            log.info("启动脚本文件已创建");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("创建启动脚本文件时发生错误", e);
        }
    }

    private void createStopScript(String serverName, String startPaht, String configPath) {
        String script = "@echo off\n" +
                "echo Stopping Nginx processes...\n" +
                "taskkill /F /IM nginx.exe\n" +
                "echo All Nginx processes have been stopped.\n" +
                "pause";

        int index = startPaht.lastIndexOf("\\");
        // 使用try-with-resources语句自动关闭资源
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(startPaht.substring(0, index) + File.separator + serverName + File.separator + serverName + "_" + STOP))) {
            // 写入脚本内容到文件
            writer.write(script);

            log.info("停止脚本文件已创建");
        } catch (IOException e) {
            e.printStackTrace();
            log.error("创建停止脚本文件时发生错误", e);
        }
    }

    @Override
    public boolean isStartServer() {
        try {
            Thread.sleep(2000);
            log.info("查询服务进程===================");
            return ServiceUtil.isNginxRun();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean startServer(NginxEntity nginxEntity) throws Exception {
        try {
            int index = nginxEntity.getStartPath().lastIndexOf("\\");
            log.info("开始执行启动命令: cd " + nginxEntity.getStartPath().substring(0, index)+ " && "+nginxEntity.getStartPath().substring(index+1));
            Runtime.getRuntime().exec("cmd /c cd "+nginxEntity.getStartPath().substring(0, index)+ " && "+nginxEntity.getStartPath().substring(index+1));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行启动脚本失败", e);
            throw e;
        }
    }

    @Override
    public boolean stopServer(NginxEntity nginxEntity) throws Exception {
        try {
            log.info("开始执行停止命令: taskkill /F /IM nginx.exe");
            Runtime.getRuntime().exec("cmd /c taskkill /F /IM nginx.exe ");
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行启动脚本失败", e);
            throw e;
        }
    }

    @Override
    public boolean restartServer(NginxEntity nginxEntity) throws Exception {
        log.info("开始执行重启命令...");
        stopServer(nginxEntity);

        startServer(nginxEntity);
        return true;
    }
    @Override
    public String readConfig(String configPath) {
        try {
            log.info("读取配置文件");
            byte[] encoded = Files.readAllBytes(Paths.get(configPath));
            return new String(encoded, StandardCharsets.UTF_8);
        } catch (IOException e) {
            e.printStackTrace();
           log.error("读取配置文件时错误",e);
            return null; // 或者抛出一个自定义的异常
        }
    }
    @Override
    public String readStart(NginxEntity nginxEntity) {
        int index = nginxEntity.getStartPath().lastIndexOf("\\");
        return "cmd /c cd " + nginxEntity.getStartPath().substring(0, index)+ " && "+nginxEntity.getStartPath().substring(index+1);
    }

    @Override
    public String readStop(NginxEntity nginxEntity) {
        return "taskkill /F /IM nginx.exe";
    }

    @Override
    public String readRestart(NginxEntity nginxEntity) {
        int index = nginxEntity.getStartPath().lastIndexOf("\\");
        return "taskkill /F /IM nginx.exe & cmd /c cd " + nginxEntity.getStartPath().substring(0, index)+ " && "+nginxEntity.getStartPath().substring(index+1);
    }

    @Override
    public void saveConfig(NginxEntity nginxEntity, String content, String type) {
        log.info("修改配置文件："+nginxEntity.getConfigPath());
        writeConfig(nginxEntity.getConfigPath(),content);
    }

}
